//
//  SearchResultViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-29.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "SearchResultViewController.h"
#import "Order.h"
#import "OrderBaseInfo.h"
#import "ImageButton.h"
#import "URLFactory.h"
#import "CONSTS.h"
#import "CustomBadge.h"
#import "MyOrderOrderDtailViewController.h"
#import "GoodDetailWebViewController.h"


@interface SearchResultViewController()

- (void)didGetOrdersFromTaoBaoServer:(TaoBaoServer *)searchTaoBaoServer_;
- (void)getOrdersIsFail:(TaoBaoServer *)searchTaoBaoServer_;
- (void)setEGORefreshTableHeaderView;

@end

@implementation SearchResultViewController

@synthesize PDic                        =           _PDic;
@synthesize tableView                   =           _tableView;
@synthesize tableViewDataSourceArray    =           _tableViewDataSourceArray;
@synthesize searchTaoBaoServer          =           _searchTaoBaoServer;
@synthesize egoRefreshTableHeaderView   =           _egoRefreshTableHeaderView;
@synthesize page_no                     =           _page_no;

- (void)dealloc
{
    LF_RELEASE_SAFELY(_PDic);
    LF_RELEASE_SAFELY(_tableViewDataSourceArray);
    LF_RELEASE_SAFELY(_searchTaoBaoServer);
    LF_RELEASE_SAFELY(_egoRefreshTableHeaderView);
    
    [_tableView release];
    [super dealloc];
}

- (id)initWithPDic:(NSDictionary *)PDic_
{
    self = [super init];
    
    if (self)
    {
        ITTDINFO(@"%@", PDic_);
        self.PDic = PDic_;
    }
    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"搜索结果";
    
    self.tableViewDataSourceArray = [NSMutableArray array];
    
    _page_no = 1;
    
    NSString *page_no_str = [NSString stringWithFormat: @"%d", _page_no];
    
    NSString *urlStr = [URLFactory search_taobao_trades_sold_get: self.PDic page_no: page_no_str];
    ITTDINFO(@"%@", urlStr);
    
    _reLoading = YES;
    
    self.searchTaoBaoServer = [[[TaoBaoServer alloc] initWithUrl: urlStr
                                                          object: self 
                                              requestIsEndSelect:@selector(didGetOrdersFromTaoBaoServer:)
                                             requestIsFailSelect: nil    
                                                    showWaitView: YES 
                                                       urlEncode: NO] autorelease];
    [_searchTaoBaoServer startAsynchronousRequest];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear: animated];
    
    NSIndexPath *indexPath = [_tableView indexPathForSelectedRow];
    [_tableView deselectRowAtIndexPath: indexPath animated: YES];
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark - 自定义函数
- (void)didGetOrdersFromTaoBaoServer:(TaoBaoServer *)searchTaoBaoServer_
{
    
     [_egoRefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading: _tableView];
    _reLoading = NO;
    
    
    BOOL serverRetunSuccess = verifyServerRetunSuccess( searchTaoBaoServer_.dic );
    if (!serverRetunSuccess)
    {
        showAlert( ALERT_TITLE, ALERT_MESSAGE );
        
        return;
    }
    
#ifdef DEBUG
    writeJsonToPlist( searchTaoBaoServer_.dic,  taobao_trades_sold_get);
#endif
    
    NSDictionary *trades_sold_get_response = [searchTaoBaoServer_.dic objectForKey: @"trades_sold_get_response"];
    ITTDINFO(@"%@", [trades_sold_get_response allKeys]);
    NSDictionary *tradesDic = [trades_sold_get_response objectForKey: @"trades"];
    
    ITTDINFO(@"%@", [tradesDic allKeys]);
    
    NSArray *tradeArray = [tradesDic objectForKey: @"trade"];
    if ([tradeArray count] <= 0)
    {
        showAlert(ALERT_TITLE, @"没有找到搜索条件下的交易");
        
        return;
    }
    
    //NSMutableArray *orderarray = [NSMutableArray arrayWithCapacity: [tradeArray count]];
    
    for (NSDictionary *orderDic in tradeArray) 
    {
        /* orderDic = {
         orders =     {
         order =         (
         {
         "num_iid" = 10893782776;
         oid = 120730605347978;
         "pic_path" = "http://img02.taobaocdn.com/bao/uploaded/i2/22942843/T2zt4AXiJMXXXXXXXX_!!22942843.jpg";
         }
         );
         };
         tid = 120730605347978;
         }
         */
        OrderBaseInfo *orderBaseInfo = [[[OrderBaseInfo alloc] init] autorelease];
        orderBaseInfo.tid = [NSString stringWithFormat: @"%@", [orderDic objectForKey: @"tid"]];
        
        NSDictionary *orders = [orderDic objectForKey: @"orders"];
        NSArray *ordersArray = [orders objectForKey: @"order"];
    
        NSMutableArray *orderarray = [NSMutableArray arrayWithCapacity: [tradeArray count]];
        for (NSDictionary *orderDic1 in ordersArray) 
        {
            Order *order = [[[Order alloc] init] autorelease];
            
            order.title = [orderDic1 objectForKey: @"title"];
            
            //因为官方给的图片太大，所以我找到了taoba的商品的图片的规律，只要把.jpg用jpg_sum.jpg替换就可以得到小的图片
            order.pic_path = [[orderDic1 objectForKey: @"pic_path"] stringByReplacingOccurrencesOfString: @".jpg" 
                                                                                              withString: @".jpg_sum.jpg"];
            order.num_iid = [NSString stringWithFormat: @"%@", [orderDic1 objectForKey: @"num_iid"]];
            order.oid = [NSString stringWithFormat: @"%@", [orderDic1 objectForKey: @"oid"]];
            
            order.numOfBrotherOrders = [ordersArray count];
            
            [orderarray addObject: order];

            ITTDINFO(@"%@", orderDic1);
            ITTDINFO(@"%@", order.title);
        }
        
        orderBaseInfo.orders = orderarray;
        
        [_tableViewDataSourceArray addObject: orderBaseInfo];
    }
    
    if ([self.tableViewDataSourceArray count] <= 0)
    {
        showAlert(ALERT_TITLE, @"没有找到搜索条件下的交易");
        
        return;
    }
    
    [_tableView reloadData];
    
    [self setEGORefreshTableHeaderView];
}

- (void)getOrdersIsFail:(TaoBaoServer *)searchTaoBaoServer_
{
    
    [_egoRefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading: _tableView];
    _reLoading = NO;
    
    [self setEGORefreshTableHeaderView];
}

- (void)setEGORefreshTableHeaderView
{
    int dd = [_tableViewDataSourceArray count];
    ITTDINFO(@"%d", dd);
    
    int ddd = [SEARCH_REAULT_PAGE_SIZE intValue] * _page_no;
    ITTDINFO(@"%d", ddd);
    
    if ([self.tableViewDataSourceArray count] >= 5 && [self.tableViewDataSourceArray count] >= ([SEARCH_REAULT_PAGE_SIZE intValue] * _page_no)) 
    {
        if (!_egoRefreshTableHeaderView)
        {
            self.egoRefreshTableHeaderView = [[[EGORefreshTableHeaderView alloc] initWithFrame: 
                                           CGRectMake(0, _tableView.contentSize.height, 320, 100)] autorelease];
            
            _egoRefreshTableHeaderView.delegate = self;
            [_tableView addSubview: _egoRefreshTableHeaderView];
            [_egoRefreshTableHeaderView refreshLastUpdatedDate];
        }
    }
    else
    {
         [_egoRefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading: _tableView];
        [_egoRefreshTableHeaderView removeFromSuperview];
        _egoRefreshTableHeaderView = nil;
        
        return;
    }
    
    _egoRefreshTableHeaderView.frame = CGRectMake(0, _tableView.contentSize.height, 320, 100);
}

- (void)viewGoodDetail:(ImageButton *)sender
{
    NSString *num_iid = sender.num_iid;
    GoodDetailWebViewController *goodDetailWebViewController = [[[GoodDetailWebViewController alloc] initWithNum_iid: num_iid] autorelease];
    
    [self.navigationController pushViewController: goodDetailWebViewController animated: YES];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableViewDataSourceArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchResultCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: 0];
        
        UIButton *imageButton = (UIButton *)[cell viewWithTag: 102];
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        imageButton.layer.shadowColor = [UIColor blackColor].CGColor;
        imageButton.layer.shadowOpacity = 0.3;
        imageButton.layer.shadowOffset = CGSizeMake(4, 5);
    }
    
    NSInteger row = [indexPath row];
    
    OrderBaseInfo *orderBaseInfo = [_tableViewDataSourceArray objectAtIndex: row];
    Order *order = [orderBaseInfo.orders objectAtIndex: 0];
    
    ITTDINFO(@"%@", order.title);
    
    ImageButton *imageButton = (ImageButton *)[cell viewWithTag: 102];
    NSURL *imageUrl = [NSURL URLWithString: order.pic_path];
    [imageButton setImageWithURL: imageUrl];
    [imageButton addTarget: self action: @selector(viewGoodDetail:) forControlEvents: UIControlEventTouchUpInside];
    imageButton.num_iid = order.num_iid;
    
    UILabel *label = (UILabel *)[cell viewWithTag: 101];
    label.text = order.title;
    
 CGSize size = bubbleView(label.text, label.font, label.frame.size.width);
    label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, size.height);
    
    
    
    
    if ([orderBaseInfo.orders count] > 1)
    {
        CustomBadge *customBadge = (CustomBadge *)[imageButton viewWithTag: 301];
        [customBadge removeFromSuperview];
        
        CustomBadge *customBadge1 = [CustomBadge customBadgeWithString:[NSString stringWithFormat: @"%d", order.numOfBrotherOrders]
                                                       withStringColor:[UIColor whiteColor] 
                                                        withInsetColor:[UIColor redColor] 
                                                        withBadgeFrame:YES 
                                                   withBadgeFrameColor:[UIColor whiteColor] 
                                                             withScale:1.0
                                                           withShining:YES];	
        customBadge1.tag = 301;
        
        CGRect rect = CGRectMake(70 - (customBadge1.frame.size.width / 2) - 3,
                                 -(customBadge1.frame.size.height / 2),
                                 customBadge1.frame.size.width, 
                                 customBadge1.frame.size.height);
        
        customBadge1.frame = rect;
        [imageButton addSubview: customBadge1];
    }else
    {
        CustomBadge *customBadge = (CustomBadge *)[imageButton viewWithTag: 301];
        [customBadge removeFromSuperview];
    }
    
    return cell;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchResultCell" owner: nil options: nil];
    UITableViewCell *cell = [cellArray objectAtIndex: 0];
    ImageButton *imageButton = (ImageButton *)[cell viewWithTag: 102];
    UILabel *label = (UILabel *)[cell viewWithTag: 101];
    
     OrderBaseInfo *orderBaseInfo = [_tableViewDataSourceArray objectAtIndex: row];
    Order *order = [orderBaseInfo.orders objectAtIndex: 0];
    NSString *title = order.title;
    CGSize size = bubbleView(title, label.font, label.frame.size.width);
    
    float height = 0.0f;
    if (size.height < imageButton.frame.size.height)
    {
        height = imageButton.frame.size.height + (imageButton.frame.origin.y * 2);
    }else
    {
        height = size.height + label.frame.origin.y * 2;
    }
    
    
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    OrderBaseInfo *orderBaseInfo = [self.tableViewDataSourceArray objectAtIndex: row];
    
    MyOrderOrderDtailViewController *myOrderOrderDtailViewController = [[[MyOrderOrderDtailViewController alloc] initWithTid: orderBaseInfo.tid] autorelease];
    [self.navigationController pushViewController: myOrderOrderDtailViewController animated: YES];
}

#pragma mark - EGORefreshTableHeaderDelegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
    _reLoading = YES;
    //刷新页码
    _page_no++;
    
    
    
    
    
    
    NSString *page_no_str = [NSString stringWithFormat: @"%d", _page_no];
    
    NSString *urlStr = [URLFactory search_taobao_trades_sold_get: self.PDic page_no: page_no_str];
    ITTDINFO(@"%@", urlStr);
    
    _reLoading = YES;
    
    self.searchTaoBaoServer = [[[TaoBaoServer alloc] initWithUrl: urlStr
                                                          object: self 
                                              requestIsEndSelect:@selector(didGetOrdersFromTaoBaoServer:)
                                             requestIsFailSelect: nil    
                                                    showWaitView: YES 
                                                       urlEncode: NO] autorelease];
    [_searchTaoBaoServer startAsynchronousRequest];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
    return _reLoading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	return [NSDate date];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{	
	[_egoRefreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	
	[_egoRefreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

@end
